package com.newbe.security.config;

import com.newbe.security.handler.MyAuthenticationFailureHandler;
import com.newbe.security.handler.MyAuthenticationSuccessHandler;
import com.newbe.security.mapper.PermissionMapper;
import com.newbe.security.service.MyAccessDecisionManager;
import com.newbe.security.service.MyAuthenticationProvider;
import com.newbe.security.service.MyInvocationSecurityMetadataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAuthenticationFailureHandler FailureHandler;
    @Autowired
    private MyAuthenticationSuccessHandler SuccessHandler;

    @Autowired
    private MyAuthenticationProvider myAuthenticationProvider;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MyAccessDecisionManager myAccessDecisionManager;

    @Autowired
    private MyInvocationSecurityMetadataSourceService myInvocationSecurityMetadataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         //注册AuthenticationProvider
       auth.authenticationProvider(myAuthenticationProvider);
    }

     @Override
    protected void configure(HttpSecurity http) throws Exception {
         //2.对登录界面允许所有用户访问

         //3.资源需要进行登录认证，且关闭跨域允许post表单请求，loginProcessingUrl：表单路径，loginPage：登录界面
         http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().formLogin()
                 .loginPage("/login").loginProcessingUrl("/loginFrom")
                 //添加成功和失败处理器
                 .successHandler(SuccessHandler).failureHandler(FailureHandler)
                 .and().csrf().disable();
         http.authorizeRequests().antMatchers("/login").permitAll();

         http.authorizeRequests().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
             @Override
             public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                 o.setSecurityMetadataSource(myInvocationSecurityMetadataSource);
                 o.setAccessDecisionManager(myAccessDecisionManager);
                 return o;
             }
         });

    }

}